package ldy.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 包名. ldy.es
 * Copyright tiens. All Rights Reserved.
 * 描述详情：es连接器
 * 创建者：liudy
 * 创建时间：2018/4/1-15:41.
 */
public class ElasticSearchConnector {
    // 服务器地址
    private static String host = "127.0.0.1";
    // 端口
    private static int port = 9300;

    private static TransportClient client = null;

    public static void main(String[] args) throws Exception{
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
        System.out.println(client);
        client.close();
    }
    /**
     * 连接客户端程序
     * @return TransportClient
     * 创建人：liudy
     * 创建时间：2018/4/3-11:28
     */
    public static TransportClient getClient(){
        try {
            if(client == null){
                Settings settings = Settings.builder()
                        .put("cluster.name", "standalone-cluster").build();
                client = new PreBuiltTransportClient(settings)
                        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }
}
